package work.linruchang;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Image;
import lombok.SneakyThrows;

import java.io.File;
import java.util.List;

/**
 * @author LinRuChang
 * @version 1.0
 * @date 2022/09/03
 * @since 1.8
 **/
public class OthreItextTest2 {


    @SneakyThrows
    public static Image toItexImage(File imageFile) {
        return new Image(ImageDataFactory.create(imageFile.getAbsolutePath()));
    }

    @SneakyThrows
    public static File imagesToPdf(List<File> imageFiles, File targetPdfFilePath) {
        if (CollUtil.isNotEmpty(imageFiles) && targetPdfFilePath != null) {
            // 创建PDF实例
            PdfWriter pdfWriter = new PdfWriter(targetPdfFilePath);
            // 管理跟踪、添加的内容
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);

            File firstImageFile = CollUtil.getFirst(imageFiles);
            Image firstImage = toItexImage(firstImageFile);
            Document document = new Document(pdfDocument, new PageSize(Convert.toFloat(firstImage.getImageWidth()), Convert.toFloat(firstImage.getImageHeight())));
            document.add(firstImage);

            List<File> removeFirstImageList = CollUtil.removeAny(imageFiles, firstImageFile);
            removeFirstImageList.stream()
                    .map(OthreItextTest2::toItexImage)
                    .forEachOrdered(image -> {
                        document.add(new AreaBreak(new PageSize(Convert.toFloat(image.getImageWidth()), Convert.toFloat(image.getImageHeight()))));
                        document.setMargins(10, 10, 10, 10);
                        document.add(image);
                    });

            document.close();
            return targetPdfFilePath;
        }
        return null;
    }

    public static void main(String[] args) {
        List<File> imagesFiles = CollUtil.list(false, FileUtil.file("D:\\截图3\\合并截图0-版权信息.jpg"), FileUtil.file("D:\\截图3\\合并截图1-小桥老树致微信读书朋友的一封信+独家视频.jpg"));
        File resultPdf = FileUtil.file("D:\\截图3\\test.pdf");
        imagesToPdf(imagesFiles, resultPdf);
    }


}
